const rightInput1 = document.querySelector(".rightInput1");
const rightInput2 = document.querySelector(".rightInput2");
const rightInput3 = document.querySelector(".rightInput3");
const login = document.querySelector(".login");

login.onclick = function(){
    checkNumber();
    let a = checkNumber();
    if (a) {
        // 发起ajax，请求注册功能，携带了用户名和密码
        ajax("http://localhost:3000/api", {
            type: "register",
            username: rightInput1.value,
            password: rightInput2.value
        }).then(res => {
            // 成功
            res = JSON.parse(res);
            // console.log(res);
            if (res.code === 1) {
                if (confirm("注册成功")) {
                    location.href = "http://localhost:3000/4.login.html";
                }
            } else if (res.code === 0) {
                // 重名失败
                alert(res.title);
                rightInput1.value = "";
                rightInput2.focus();
            } else if (res.code === 2) {
                // 数据库错误
                alert(res.title);
            }
        }, code => {
            // 失败
            console.log(code);
        })
    }
}


function ajax(url, data) {
    let str = "";
    for (let i in data) {
        str += `${i}=${data[i]}&`
    }
    url += "?" + str;

    const xhr = new XMLHttpRequest();
    xhr.open("get", url);
    xhr.send();

    return new Promise((resolve, reject) => {
        xhr.onload = function () {
            if (xhr.status === 200) {
                resolve(xhr.responseText);
            } else {
                reject(xhr.status);
            }
        }
    })
}
// 正则验证
function checkNumber() {
    var phone = document.querySelector('.rightInput1').value;
    if (!(/^1(3|4|5|6|7|8|9)\d{9}$/.test(phone))) {
        alert("手机号码有误，请重填");
        return 0;
    } else {
        return 1;
    }
}

